<template>
    <div class="dict-data-container">
        <FilterSearch
            :searchItems="searchItems"
            :showAddButton="showAddButton"
            :showImportButton='showImportButton'
            @query="handleQuery"
            @add="handleAdd"
            @import='handleImport'
        />
        <AutoTable
            :tableData="tableData"
            :columns="columns"
            @operate="handleOperate"
        />
        <Pagination
            :total="total"
            :pageSize="pageSize"
            :currentPage="currentPage"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
        <EditDialog
            ref="editDialogRef"
            :visible="editDialogVisible"
            :dialogType="editDialogType"
            :editItems="editItems"
            @successCallBack="editCallBack"
            @close="handleClose"

        />
        <ImportDialog
            ref="importDialogRef"
            :visible="importDialogVisible"
            :maxSize="maxSize"
            :fileType="fileType"
            :importUrl="importUrl"
            @close="handleClose"
        />
    </div>
</template>
<script setup>
import './index.css';
import { reactive, ref, markRaw } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { View, Switch, Edit } from '@element-plus/icons-vue'

import FilterSearch from '@/components/filterSearch/index.vue';
import AutoTable from '@/components/autoTable/index.vue';
import Pagination from '@/components/pagination/index.vue';
import EditDialog from '@/components/editDialog/index.vue';
import ImportDialog from '@/components/importDialog/index.vue';

import { dictDataApi } from '@/api';
import { useDownBlob } from '@/utils';

// FilterSearch params
const searchItems = ref([
    {
      label: '字典编码',
      vModel: 'code',
      type: 'input',
      initialValue: ''
    },
    {
      label: '状态',
      vModel: 'status',
      type: 'select',
      optionsCode: 'forbidden_flag',
      initialValue: ''
    }
]);  
const showAddButton = ref(true);
const showImportButton = ref(true);
const searchCache = ref({});


// AutoTable params
const tableData = ref([]);
const columns = ref([
    {
      label: '字典编码',
      prop: 'code',
      width: '140px'
    },
    {
      label: '字典标签',
      prop: 'label',
      width: '120px'
    },
    {
      label: '字典值',
      prop: 'value',
    },
    {
      label: '排序',
      prop: 'order',
    },
    {
      label: '状态',
      prop: 'status',
      type: 'switch'
    },
    {
      label: '操作',
      prop: 'operate',
      fixed: 'right',
      type: 'action',
      align: 'left',
      width: '140px',
      operate: [
        {label: '详情', type: 'view', icon: markRaw(View)},
        {label: '编辑', type: 'edit', icon: markRaw(Edit)}, 
        {label: '切换', type: 'switch', icon: markRaw(Switch)},
      ]
    }

]);

// Pagination params
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);

// edit Dialog params
const editDialogVisible = ref(false);
const editDialogType = ref('add');
const editItems = ref([
    {
      label: 'id',
      vModel: '_id',
      type: 'forbidden',
      initialValue: '',
    },
    {
      label: '字典编码',
      vModel: 'code',
      type: 'input',
      initialValue: '',
    },
    {
      label: '字典标签',
      vModel: 'label',
      type: 'input',
      initialValue: ''
    },
    {
      label: '字典值',
      vModel: 'value',
      type: 'input',
      initialValue: ''
    },
    {
      label: '排序',
      vModel: 'order',
      type: 'input',
      initialValue: ''
    }
]);  

// import Dialog params
const importUrl = ref('/sys/dict-data/import');
const importDialogVisible = ref(false);
const maxSize = ref(5 * 1024 * 1024);
const fileType = ref(['xlsx', 'xls', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']);

// filterSearch Api
const handleQuery = async (params) => {
    // 调用接口获取数据
    searchCache.value = params;
    const reqParams = {
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        ...params
    }
    const res = await dictDataApi.getDictData(reqParams);
    if (res.code === 200) {
      tableData.value = res.data.rows;
      total.value = res.data.total;
    }
};

// EditDialog Api
const handleAdd = () => {
    editDialogType.value = 'add';
    editDialogVisible.value = true;
};
const editCallBack = async (type, params) => {
    if (type === 'add') handleAddCallBack(params);
    else if (type === 'edit') handleEditCallBack(params);
} 
const handleAddCallBack = async (params) => {
    const res = await dictDataApi.createDictData(params);
    if (res.code === 200) {
        editDialogVisible.value = false;
        ElMessage.success('新增成功');
        handleQuery();
    }
}
const handleEditCallBack = async (params) => {
    const res = await dictDataApi.updateDictData(params._id, params);
    if (res.code === 200) {
        editDialogVisible.value = false;
        ElMessage.success('变更成功');
        handleQuery();
    }
}

// importDialog Api
const handleImport = () => {
    importDialogVisible.value = true;
}
const handleClose = () => {
    importDialogVisible.value = false;
    editDialogVisible.value = false;
}

// Pagination Api
const handleSizeChange = (size) => {
    pageSize.value = size;
    handleQuery(searchCache.value);
};
const handleCurrentChange = (page) => {
    currentPage.value = page;
    handleQuery(searchCache.value);

};

// AutoTable Api
const handleOperate = (type, row) => {
    if (type === 'edit') {
      editDialogType.value = 'edit';
      initEditItems(row);
      editItems.value[1].forbidden = true;
      editDialogVisible.value = true;

    }
    else if (type === 'view') {
      editDialogType.value = 'view';
      initEditItems(row);
      editDialogVisible.value = true;
    }
    else if (type === 'switch') {
      handleSwitch(row);
    }
}
const initEditItems = (row) => {
  editItems.value.forEach(item => {
    item.initialValue = row[item.vModel];
  })
}
const handleSwitch = (row) => {
  ElMessageBox.confirm(
    '确定切换当前字典类型状态吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      const res = await dictDataApi.switchDictData(row._id)
      if (res.code === 200) {
        ElMessage({ type: 'success', message: '切换成功!' });
        handleQuery();
      }
    })
    .catch(() => {
      ElMessage({ type: 'info', message: '取消切换!' })
    })
}

</script>